import fs from "fs";
import path from "path";
export function ensureDir(dirPath: string): void {
  try {
    fs.statSync(dirPath);
    const files = fs.readdirSync(dirPath);
    files.forEach((v) => {
      fs.unlinkSync(path.join(dirPath, v));
    });
  } catch (err) {
    console.log(err);
    fs.mkdirSync(dirPath);
  }
}
export function log(name: string, err: any): void {
  console.log(`----- error in ${name} -----\n`);
  console.log(err);
  console.log("----------");
}
export function edit<T>(filename: string, editor: (obj: T) => T): void {
  const dataDirPath = path.join(__dirname, "../data");
  const data: T[] = JSON.parse(
    fs.readFileSync(path.join(dataDirPath, filename), { encoding: "utf-8" })
  ).data;
  const result = {
    data: data.map((v) => {
      return editor(v);
    }),
  };
  fs.writeFileSync(path.join(dataDirPath, filename), JSON.stringify(result));
}
